package com.jt.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

public class SecondKillDemo01 {
    static void init(){
        //1.与redis建立连接
        Jedis jedis = JedisDataSource.getConnection();
        //2.初始数据
        jedis.set("ticket", "1");
        jedis.set("money", "0");
        //3.释放资源
        jedis.close();
    }

    /**
     * 构建秒杀业务
     */
    static void secondKill(){
       //1.建立连接
        Jedis jedis = JedisDataSource.getConnection();
       //2.修改票数和钱数
        jedis.watch("ticket");//监控,添加乐观锁
        Transaction multi = jedis.multi();
        try {
            multi.decr("ticket");
            multi.incrBy("money", 100);
            List<Object> exec = multi.exec();
            System.out.println(exec);
        }catch (Exception e){
            multi.discard();
        }finally {
            jedis.unwatch();
            //3.释放资源
            jedis.close();
        }
    }
    public static void main(String[] args) {
        //0.执行数据初始化(在redis中创建一些初始数据)
        init();
        //1.创建秒杀线程对象
        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                secondKill();
            }
        });
        Thread t2=new Thread(()->{
                secondKill();
        });
        //2.执行描述操作
        t1.start();
        t2.start();
    }
}
